<template>
  <div class="wrap">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="form" size="mini">
        <el-form-item label="集成测试名称">
          <el-input v-model="form.name" placeholder="请输入集成测试名称"></el-input>
        </el-form-item>
        <el-form-item label="测试状态">
          <el-select v-model="form.status" size="mini" placeholder="请选择测试状态">
            <el-option v-for="item in testTypeArray" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="getSelect">查询</el-button>
          <el-button icon="el-icon-refresh"  @click="reset">重置</el-button>
          <el-button icon="el-icon-circle-plus-outline" type="success" @click="add">添加</el-button>
          <el-button icon="el-icon-delete" type="danger" @click="somedelete">批量删除</el-button>
          <el-button icon="el-icon-caret-right" type="success" @click="ImmExecution" >立即执行</el-button>
          <el-button icon="el-icon-refresh" type="success" @click="refresh" >刷新</el-button>
          <cloum @checkCall="checkCall" :checkbooks="checkList" style="margin-left: 30px" />
        </el-form-item>
      </el-form>
    </div>

    <!--数据列表-->
    <div class="table">
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="dataList"
        :expand-row-keys="expands"
        height="680"
        @select = "deleteaAll"
        @select-all = "deleteaAll"
        @selection-change="selectionChange" :row-key="getRowKeys">
        <el-table-column type="selection" width="55" :reserve-selection="true" align="center"></el-table-column>
        <!--<el-table-column type="expand">
          <template slot-scope="scope" style="font-size: 20px">
            <div v-if="scope.row.interfaceArr" style="width: 100%;height:50px;line-height: 50px;" v-for="(item,index) in scope.row.interfaceArr" :key="index">
              <span class="inName">{{item.interfaceName}}</span>
              <span class="inNameprograss">
                <el-tooltip class="item" effect="dark" :content="prograssMsg(item)" placement="top" style="width: 190px;margin-left: 5px">
                  <el-progress v-if="!doStatus(item,true).state" :status="doStatus(item,true).string" :percentage="doStatus(item,true).zyNumber"></el-progress>
                  <el-progress v-else :percentage="doStatus(item,true).zyNumber"></el-progress>
                </el-tooltip>
              </span>
            </div>
          </template>
        </el-table-column>-->
        <el-table-column  label="序号" type="index" width="60"></el-table-column>
        <el-table-column  v-if="checkList.indexOf('测试名称') >=0" label="集成测试名称" prop="name" width="330" align="left"></el-table-column>
        <el-table-column  v-if="checkList.indexOf('测试状态') >=0" label="测试状态" prop="status" width="210">
          <template slot-scope="scope">
            <span v-if="scope.row.lastTestInterfaceTotal === null">暂无测试记录</span>
            <el-tooltip v-else class="item" effect="dark" :content="prograssMsg(scope.row)" placement="top">
              <el-progress v-if="!doStatus(scope.row).state" :status="doStatus(scope.row).string" :percentage="doStatus(scope.row).zyNumber"></el-progress>
              <el-progress v-else :percentage="doStatus(scope.row).zyNumber"></el-progress>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column  v-if="checkList.indexOf('测试时间') >=0" label="测试时间" prop="updateTime">
          <template slot-scope="scope">
            <span v-if="scope.row.lastTestTime">
              {{ $time(scope.row.lastTestTime)}}
            </span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-button @click="updateOrDetail(scope.row, true)" type="text" size="small">
              <el-tooltip class="item" effect="dark" content="配置详情" placement="bottom"><i class="el-icon-setting"></i></el-tooltip></el-button>
            <el-button @click="detail(scope.row)" type="text" size="small">
              <el-tooltip class="item" effect="dark" content="测试详情" placement="bottom"><i class="el-icon-view"></i></el-tooltip></el-button>
            <el-button @click="updateOrDetail(scope.row)" type="text" size="small">
              <el-tooltip class="item" effect="dark" content="修改" placement="bottom"><i class="el-icon-edit"></i></el-tooltip>
            </el-button>
            <el-button  @click="update(scope.row)" v-if="scope.row.status == 0||scope.row.status == 2" type="text" size="small">
              <el-tooltip class="item" effect="dark" content="开始" placement="bottom"><i class="el-icon-caret-right"></i></el-tooltip>
            </el-button>
            <el-button  @click="update(scope.row)" v-else type="text" size="small">
              <el-tooltip class="item" effect="dark" content="暂停" placement="bottom"><i class="el-icon-bell"></i></el-tooltip>
            </el-button>
            <el-button @click="oneDelete(scope.row)" type="text" size="small">
              <el-tooltip class="item" effect="dark" content="删除" placement="bottom"><i class="el-icon-delete"></i></el-tooltip></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pager">
      <el-pagination
        @size-change="sizeChange"
        @current-change="currentChange"
        :current-page="form.pageNum"
        :page-sizes="[10,20,30,50]"
        :page-size="form.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal">
      </el-pagination>
    </div>

    <!-- 配置详情弹窗 -->
    <config-info v-if="confdialog" @closeCall="closeCall" :conf-dialog="confdialog" :detail="integrateDetail" :type="type" :disabled="disabled"/>

    <!--详情弹框-->
    <detail-test v-if="detaildialog" @closeCall="closeCall" :detail-data="detaildata" :detail-dialog="detaildialog" />
    <!--立即执行弹框-->
    <el-dialog  :visible.sync="Immdialog" width="30%">
      <el-form :model="form" :rules="rules" ref="form" class="concurrentCSS">
        <el-form-item label="并发数" label-width="80px" prop="number">
          <el-input v-model="form.number" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="startExecution('form')" size="small">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { formatDateTime } from "@/libs/utils"
  import ConfigInfo from './ConfigInfo';
  import DetailTest from './DetailTest';
  import Cloum from "@/rdComponent/common/Cloum";

  export default {
    components: {
      Cloum,
      DetailTest, ConfigInfo
    },
    data () {
      return {
        expands:[],
        dialog: false,
        confdialog: false,
        Immdialog:false,
        detaildialog:false,
        detaildata:"",
        form: {
          name: "",
          status: "",
          pageNum: 1,
          pageSize: 10,
          number:"",
        },
        loading: true,
        pageTotal: 0,
        dataList: [],
        testTypeArray: [],
        multipleSelection: [],
        deleterArr:[],
        rules: {
          number: [
            { required: true, message: '请填写并发数', trigger: 'blur' }
          ]
        },
        integrateDetail: {},
        type: 0,
        disabled: false,
        checkList: ["测试名称","测试状态","测试时间"]
      }
    },
    mounted(){

      this.getList();
      this.getIntegrationTestType();
      this.interval = setInterval(this.getListToUpdate,2000);
    },
    beforeDestroy() {
      clearInterval(this.interval);
    },
    methods: {
      checkCall(val) {
        this.checkList = val;
      },

      /**动态刷新**/
      regetlist(){
        setInterval(()=>{
          this.axios.get("/api/integration/test/page",{
            params: this.form
          }).then((rsp)=>{
            rsp.data.data.list.forEach((item)=>{
              this.prograssBar(item);
              this.prograssMsg(item);
            })
          })
        },2000);
      },
      /** 进度条**/
      prograssBar(row){
        if (row.lastTestSuccessInterfaceTotal/row.lastTestInterfaceTotal){
          return row.lastTestSuccessInterfaceTotal/row.lastTestInterfaceTotal*100;
        }else{
          return 0;
        }
      },
      prograssMsg(row){
        if (row.lastTestInterfaceTotal) {
          return row.lastTestSuccessInterfaceTotal+"/"+row.lastTestInterfaceTotal
        }else{
          return 0+"/"+0
        }
      },
      /*获取测试状态接口*/
      getIntegrationTestType(){
        this.axios.get("/api/integration/test/record/status").then(rsp => {
          let array = [],aimData = rsp.data.data;
          Object.keys(aimData).forEach(function(key){
            let obj = {};
            obj.value = key;
            obj.label = aimData[key];
            array.push(obj)
          });
          this.testTypeArray = array;
        })
      },
      /** 点击查询按钮**/
      getSelect(){
        this.getList();
      },

      /*进行进度条的状态展示的选择的方法*/
      doStatus(item,type) {
        let total , alltotal, state;
        if(!type){
          total = item.lastTestSuccessInterfaceTotal;
          alltotal = item.lastTestInterfaceTotal;
          state = item.lastTestStatus;
        }else {
          total = item.successTotal;
          alltotal = item.total;
          state = item.status;
        }


        /*通过比对两个值进行展示结果的显示*/
        /*不纯在或者为null的时候就为0*/
        // let keyReturn = false;
        // if (total === null || alltotal === null) {
        //   keyReturn = true;
        // }

        // if(keyReturn){
        //   this.$message.error("配置参数异常，请联系管理员！");
        //   return false;
        // }

        if (total === null ) {
          total = 0
        }

        if (alltotal === null || alltotal == 0) {
          alltotal = 1
        }


        let number = parseInt((total / alltotal) * 100);
        let backString = "", myState = false;
        switch (state) {
          case '0':
            /*执行中*/
            myState = true;
            break;
          case '1':
            /*执行成功*/
            backString = "success";
            break;
          case '2':
            /*执行失败*/
            backString = "exception";
            break;
        }

        return {
          state: myState,
          zyNumber: number,
          string: backString
        }
      },
      /** 点击重置按钮**/
      reset(){
        this.form.name = "";
        this.form.status = "";
        this.getList();
      },
      /**获取数据列表**/
      getList(){
        this.axios.get("/api/integration/test/page",{
          params: this.form
        }).then((rsp)=>{
          this.pageTotal = rsp.data.data.total;
          this.dataList = rsp.data.data.list;
          this.dataList.forEach((item)=>{
            this.expandChange(item)
          });
          setTimeout(() => {this.loading = false}, 500);
        }).catch(()=>{
          setTimeout(() => {this.loading = false}, 500);
        })
      },
      /**监听选择table**/
      selectionChange(val) {
        this.multipleSelection = val;
      },
      /**分页Key值**/
      getRowKeys(row) {
        return row.id;
      },
      /**改变显示条数**/
      sizeChange(val) {
        this.form.pageSize = val;
        this.getList();
      },
      /**改变页数**/
      currentChange(val) {
        this.form.pageNum = val;
        this.getList();
      },
      /**刷新**/
      refresh() {
        this.expands = [];
        this.loading = true;
        this.getList();
      },
      detail(row,expends) {
        //this.expands = [];
        this.detaildialog = false;
        this.$nextTick(() => {
          this.detaildata = row;
          this.detaildialog = true;
        })
      },
      /**删除**/
      oneDelete(row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleterArr = [];
          this.deleterArr.push(row.id);
          this.axios.delete("/api/integration/test",{
            data: this.deleterArr
          }).then((rsp)=>{
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.deleterArr = [];
            this.getList();
            setTimeout(() => {this.loading = false}, 500);
          }).catch(()=>{
            setTimeout(() => {this.loading = false}, 500);
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      deleteaAll(selection){
        this.deleterArr=[];
        selection.forEach((item)=>{
          console.log(item);
          this.deleterArr.push(item.id)
        })
      },
      somedelete(){
        if (this.deleterArr.length>0){
          this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.axios.delete("/api/integration/test",{
              data: this.deleterArr
            }).then((rsp)=>{
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getList();
              setTimeout(() => {this.loading = false}, 500);
            }).catch(()=>{
              setTimeout(() => {this.loading = false}, 500);
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        }else{
          this.$message.error('请至少勾选一个集成测试！');
        }

      },
      /**关闭添加弹窗回调**/
      closeCall() {
        this.dialog = false;
        this.confdialog = false;
        this.refresh();
      },
      /**立即执行**/
      ImmExecution(){
        this.form.number="";
        if (this.deleterArr.length>0){
          this.Immdialog=true;
        }else{
          this.$message.error('请至少勾选一个集成测试！');
        }
      },
      startExecution(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            this.Immdialog=false;
            this.axios.put("/api/integration/test/execute/"+this.form.number,this.deleterArr)
              .then((rsp)=> {
                console.log(rsp);
                if(rsp.data.msg =="success"){
                  this.$message({
                    type: 'success',
                    message: '执行成功!'
                  });
                  this.getList();
                }
              })
          } else {
            return false;
          }
        });
      },

      /**展开行**/
      expandChange(row){
        if(row.lastTestRecordId !== null){
          this.axios.get("/api/integration/test/interfaces/"+row.lastTestRecordId)
            .then((rsp)=> {
              for (let i = 0; i < this.dataList.length; i++) {
                if (row.lastTestRecordId == this.dataList[i].lastTestRecordId) {
                  this.dataList[i].interfaceArr = rsp.data.data;
                  break;
                }
              }
              // row.interfaceArr = rsp.data.data;
            })
        }else {
          row.interfaceArr = [];
        }
      },
      update(row) {
        let updateArr = [{
          "id": row.id,
          "status": row.status
        }];
        this.axios.post("/api/integration/test/batchUpdateStatus",updateArr)
          .then((rsp)=> {
            if(rsp.data.status === 0){
              this.$message({
                type: 'success',
                message: '执行成功!'
              });
              this.getList();
            }
          })
      },
      /**添加**/
      add() {
        this.$router.push({
          name: "addOrUpdate",
          params: {
            type: 0,
            disabled: false,
            detail: {}
          }
        })
      },
      updateOrDetail(row, type){
        this.axios.get(`/api/integration/test/${row.id}`).then((rsp)=> {
          if(rsp.data.status === 0){
            this.integrateDetail = rsp.data.data;
            if (type) {
              this.disabled = true;
              this.type = 2;
              this.confdialog = false;
              this.$nextTick(() => {
                this.confdialog = true
              })
            }
            else {
              this.$router.push({
                name: "addOrUpdate",
                params: {
                  type: 1,
                  disabled: false,
                  detail: rsp.data.data
                }
              })
            }
          }
        })
      },
      /**获取数据列表用于刷新**/
      getListToUpdate(){
        let tmpDataList = [];
        this.axios.get("/api/integration/test/page",{
          params: this.form
        }).then((rsp)=>{
          this.tmpDataList = rsp.data.data.list;
          for(let i = 0;i < this.tmpDataList.length; i++){
            if(this.tmpDataList[i].lastTestSuccessInterfaceTotal != null)
              this.dataList[i].lastTestSuccessInterfaceTotal = this.tmpDataList[i].lastTestSuccessInterfaceTotal;
            if(this.tmpDataList[i].lastTestInterfaceTotal != null)
              this.dataList[i].lastTestInterfaceTotal = this.tmpDataList[i].lastTestInterfaceTotal;
            if(this.tmpDataList[i].lastTestStatus != null)
              this.dataList[i].lastTestStatus = this.tmpDataList[i].lastTestStatus;
          }
        })
      },
    },
    filters: {
      formatDate(time) {
        return formatDateTime(new Date(time), 'yyyy-MM-dd hh:mm:ss');
      }
    },
  }
</script>

<style scoped lang="less">
  .wrap{
    border: 20px solid #e2eaed;
    height: 100%;
    width: 100%;
    padding: 20px 0 20px 20px;
    background: #fff;
    .inName{
      margin-left: 113px;
      padding:0 10px;
      display: inline-block;
      width: 330px;
    }
    .inNameprograss{
      display: inline-block;
      width: 310px;
    }

    .search-bar {
      background: #fff;
      /*padding: 15px;*/
      padding-bottom: 0;
    }

    .table {
      height: calc(100% - 47px - 32px);
      background: #fff;
      margin-top: 10px;
      position: relative;
      overflow-x: hidden;
    }

    .pager {
      position: absolute;
      bottom: 30px;
      right: 30px;
    }
    .concurrentCSS{
      width: 80%;
      margin: 20px;
      height: 40px;

    }
  }
</style>


